<template>
  <a-drawer :width="640" v-model:visible="visible" class="custom-class" placement="right" :maskClosable="false"
    :closable="false">
    <a-spin :spinning="AISpinging" tip="生成中...">
      <div class="drawer-header">
        <div class="drawer-header-title">
          <close-outlined class="drawer-close" @click="onClose" />
          <div v-if="!ismiaoshu" class="drawer-title">成片标题</div>
          <div v-if="ismiaoshu" class="drawer-title">成片描述</div>
        </div>
      </div>
      <a-form ref="formRef" style="margin-top: 20px" :label="horizontal" :model="titleList" @finish="onFinish"
        @finishFailed="onFinishFailed">
        <!-- 批量AI生成顶部提示信息 -->
        <div class="title_tip" style="
            display: flex;
            align-items: center;
            justify-content: space-between;
          ">
          <div style="display: flex; align-items: center">
            <!-- <a-popover v-if="AILoading">
              <template #content> AI扩写生产中，请耐心等待 </template>
              <a-button disabled class="ai_disabled" size="small" style="display: flex !important; align-items: center">
                <template #icon>
                  <cu-icon type="icon-AIxiezuozhushou"
                    style="color: #2580fd; font-size: 18px; margin-top: 3px"></cu-icon>
                </template>
                AI扩写
              </a-button>
            </a-popover> -->
            <!-- <a-button v-else size="small" @click="addAIExpansion" style="display: flex; align-items: center">
              <template #icon>
                <cu-icon type="icon-AIxiezuozhushou" style="color: #2580fd; font-size: 18px; margin-top: 3px"></cu-icon>
              </template>
              AI扩写
            </a-button> -->
            <a-button   type="primary" ghost size="small" class="ai-batch-writing-titles" @click="AIBatchWritingTitles">AI批量写标题</a-button>
            <span v-if="AILoading" style="font-size: 14px; flex: 1; margin: 0 15px">预计生成：<span
                style="font-weight: 600">{{
                AIExpanSionTotal
                }}</span>，已生成：<span style="font-weight: 600">{{
                AIExpanSionCount
                }}</span></span>
            <a-progress size="small" v-if="AILoading" :percent="AIExpansionPercent" style="width: 140px" />
          </div>

          <div class="right">
            <a-button type="default" size="small" style="margin-right: 10px" @click="topicImport()">话题导入</a-button>
            <a-button :disabled="AILoading" type="default" size="small" style="margin-right: 10px"
              @click="copywritingImport()">文案库导入</a-button>
            <a-button :disabled="AILoading" type="default" size="small" style="margin-right: 10px"
              @click="openFangxie()">文案仿写</a-button>
            <a-button :disabled="AILoading" type="default" size="small" @click="riskWordDetnHandle()">风险词检测</a-button>
          </div>
        </div>
        <div v-for="(item, index) in titleList" :key="index">
          <!-- 标题 -->
          <div style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-top: 10px;
            ">
            <span v-if="!ismiaoshu" style="margin-right: 10px; font-weight: 600">标题_{{ index + 1 }}</span>
            <span v-if="ismiaoshu" style="margin-right: 10px; font-weight: 600">描述_{{ index + 1 }}</span>
            <delete-outlined class="del_btn" v-if="titleList.length > 1" @click="deleteTitle(index)" />
          </div>
          <div class="title_item" style="padding: 10px 10px 0">
            <!-- 标题输入框 -->
            <template v-if="
                PlatFormValue == 'xiaohongshu' || PlatFormValue == 'bilibili'
              ">
              <a-form-item label="标题" style="margin-bottom: 0 !important; height: 30px" :name="[index, 'text']" :rules="
                  PlatFormValue == 'bilibili'
                    ? [
                        {
                          required: true,
                          message: '请输入标题',
                        },
                        {
                          max: TitleTextTipRules.maxlength,
                          message: `标题最大长度为${TitleTextTipRules.maxlength}`,
                        },
                      ]
                    : [
                        {
                          max: TitleTextTipRules.maxlength,
                          message: `标题最大长度为${TitleTextTipRules.maxlength}`,
                        },
                      ]
                ">
                <a-input :disabled="AILoading" v-model:value="titleList[index].text" show-count
                  :maxlength="TitleTextTipRules.maxlength" placeholder="好的作品标题可获得更多浏览" :bordered="false">
                  <template #prefix>
                    <a-tooltip :title="TitleTextTipRules.tips">
                      <question-circle-outlined style="color: rgba(0, 0, 0, 0.45)" />
                    </a-tooltip>
                  </template>
                </a-input>
              </a-form-item>
              <!--标题 AI扩写/改写 -->
              <div class="AI_expend">
                <s-space>
                  <a-tooltip placement="top">
                    <template #title>
                      <span>对当前内容进行改写</span>
                    </template>
                    <a-button size="small" type="link" :disabled="AILoading || AISpinging" @click="
                      handleAIRequest({
                        ...item,
                        clickType: 'AIRewriting',
                        index,
                        labelType: 'title',
                      })
                    "><cu-icon style="margin-right: 3px" type="icon-AIgaixie"></cu-icon>AI改写</a-button>
                  </a-tooltip>
                  <a-tooltip placement="top">
                    <template #title>
                      <span>对当前内容进行扩写一条</span>
                    </template>
                    <a-button size="small" type="link" :disabled="AILoading || AISpinging" @click="
                      handleAIRequest({
                        ...item,
                        clickType: 'AIExpand',
                        index,
                        labelType: 'title',
                      })
                    "><cu-icon style="margin-right: 3px" type="icon-iconkuoxie"></cu-icon>AI扩写</a-button>
                  </a-tooltip>
                </s-space>
              </div>

              <a-divider style="border-color: #e0e0e0; margin: 5px 0 !important" dashed />
            </template>

            <!-- 简介输入框 -->
            <a-form-item :label="
                PlatFormValue == 'xiaohongshu' || PlatFormValue == 'bilibili'
                  ? '简介'
                  : ''
              " :name="[index, 'caption']" :rules="
                PlatFormValue == 'kuaishou'
                  ? [
                      {
                        required: true,
                        message: '请输入',
                      },
                      {
                        max: CapttionTipRules?.maxlength,
                        message: `作品简介不能超过${CapttionTipRules?.maxlength}字限制，含空格`,
                      },
                    ]
                  : []
              ">
              <a-textarea :disabled="AILoading" :autoSize="{ minRows: 3, maxRows: 4 }"
                v-model:value="titleList[index].caption" show-count :maxlength="CapttionTipRules?.maxlength"
                :bordered="false">
              </a-textarea>
            </a-form-item>
            <!--简介 AI扩写/改写 -->
            <div class="AI_expend">
              <s-space>
                <a-tooltip placement="top">
                  <template #title>
                    <span>对当前内容进行改写</span>
                  </template>
                  <a-button size="small" type="link" :disabled="AILoading || AISpinging" @click="
                    handleAIRequest({
                      ...item,
                      clickType: 'AIRewriting',
                      index,
                      labelType: 'desc',
                    })
                  "><cu-icon style="margin-right: 3px" type="icon-AIgaixie"></cu-icon>AI改写</a-button>
                </a-tooltip>

                <a-tooltip placement="top">
                  <template #title>
                    <span>对当前内容进行扩写一条</span>
                  </template>
                  <a-button size="small" type="link" :disabled="AILoading || AISpinging" @click="
                    handleAIRequest({
                      ...item,
                      clickType: 'AIExpand',
                      index,
                      labelType: 'desc',
                    })
                  "><cu-icon style="margin-right: 3px" type="icon-iconkuoxie"></cu-icon>AI扩写</a-button>
                </a-tooltip>
              </s-space>
            </div>
            <!-- 分割线 -->
            <a-divider style="border-color: #e0e0e0; margin: 10px 0 !important" dashed />

            <!-- 添加话题提示 -->
            <template v-if="PlatFormValue != 'xiaohongshu'">
              <div style="display: flex" v-if="
                !(PlatFormValue == 'kuaishou' || PlatFormValue == 'bilibili')
              ">
                <a-form-item style="margin-bottom: 0 !important">
                  <span style="margin-right: 3px; color: var(--ss-primary-color)">#添加话题</span>
                </a-form-item>
                <a-form-item style="margin-bottom: 0 !important; flex: 1">
                  <!-- item.isSpining -->
                  <a-spin :spinning="!!item.isSpining">
                    <a-select :disabled="AILoading" v-model:value="item.hashtag_name" mode="tags" :maxTagTextLength="10"
                      :maxTagCount="5" :token-separators="[',']" @change="tagChange($event, item, item.keyWordsList)"
                      :bordered="false" placeholder="输入话题按回车键选中" style="width: 100%" :options="item.keyWordsList"
                      optionLabelProp="label"></a-select>
                  </a-spin>
                </a-form-item>
                <a-form-item label="关键词组">
                  <a-select style="width: 150px" allowClear @change="groupSelChange(item, index)" :disabled="AILoading"
                    v-model:value="item.ai_keyword_group_id" placeholder="选择关键词组"
                    :options="item.keyWordsGroupList"></a-select>
                </a-form-item>
              </div>
            </template>
            <template v-else>
              <a-form-item>
                <template #label>
                  <span class="mr-5">话题</span>
                  <a-tooltip>
                    <template #title>
                      <span>需要先选择账号</span>
                    </template>
                    <QuestionCircleOutlined />
                  </a-tooltip>
                </template>
                <a-select v-model:value="item.hashtag_name" :disabled="!accountId" show-search
                  @search="XHS_Status.handleSearch" :filter-option="false" @change="XHS_Status.handleChange"
                  mode="multiple" :maxTagCount="20" placeholder="请选择话题">
                  <a-select-option :disabled="item?.hashtag_name?.length > 19 &&
                    !item?.hashtag_name?.includes(item.key)
                    " :value="item.key" v-for="(item, index) in topicList" :key="item.key">{{ item.name
                    }}</a-select-option>
                </a-select>
                <div class="mt-5 text-gray-6">您可以添加20个话题</div>
              </a-form-item>
            </template>


          </div>
        </div>
        <!-- 添加成片标题按钮 v-if="!ismiaoshu"-->
        <a-button v-if="!ismiaoshu" :disabled="AILoading" style="margin-top: 20px" block type="dashed"
          @click="addTitle"><plus-outlined />添加成片标题</a-button>

           <a-button v-if="ismiaoshu" :disabled="AILoading" style="margin-top: 20px" block type="dashed"
          @click="addTitle"><plus-outlined />添加成片描述</a-button>
      </a-form>
    </a-spin>
    <template #footer>
      <div style="text-align: right">
        <a-button style="margin-right: 8px" @click="onClose" :disabled="AISpinging">取消</a-button>
        <a-button :disabled="AILoading || AISpinging" type="primary" @click="submitHandle">确定</a-button>
      </div>
    </template>
  </a-drawer>
  <!-- AI扩写 -->
  <AIExpansion ref="aiExpansionRef" @onConfirm="onConfirmAIExpansion" />
  <RiskWordDetection ref="riskWordDetection" />

  <!-- 文案仿写组件 -->
  <TextImitationDialog ref="TextImitationDialogRef" :isComponents="true" @getTextArr="getTextArr"></TextImitationDialog>

  <!-- 文案库 -->
  <CopyLibraryModal ref="copyLibraryModal" selectType="checkbox" @importSuccess="closeChooseMaterial" />

  <!-- 话题导入 -->
  <TopicImportModal :visible="topicImporVisible" @closeChange="closeChange"
    @XHS_importChange="XHS_Status.XHS_importChange" @importChange="importChange" :PlatFormValue="PlatFormValue"
    :accountList="accountList" />
  <!-- 充值弹窗 -->
  <vipModal :visible="vipVisible" @close="vipVisible = false"></vipModal>

  <!-- AI写标题 -->
  <AIWritingTitle :visible="writingTitleVisible" :titleListNum="titleListNum" @close="closeWritingTitleChange" @submit="submitChange" :wordsNum="TitleTextTipRules.maxlength" :number="0" type="1"/>

</template>

<script>
import {
  defineComponent,
  ref,
  reactive,
  toRefs,
  createVNode,
  computed,
  onMounted,
  watch
} from "vue";
import {
  PlusOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  CloseOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import AIExpansion from "./AIExpansion.vue";
import { Modal } from "ant-design-vue";
import _ from "lodash";
import RiskWordDetection from "../../MuseMixedCut/mixedCutCreat/components/riskWordDetecDrawer.vue";
import request from "@/common/utils/request";
// 文案仿写
import TextImitationDialog from "@/views/shotstack/components/TextImitationDialog/index.vue";
import { useRoute, useRouter } from "vue-router";
import { error } from "jquery";
import { containsProp } from "@vueuse/core/index.cjs";
// 文案库组件
import CopyLibraryModal from "@/components/AddTextModal/CopyLibraryModal.vue";

// 话题导入
import TopicImportModal from "./TopicImportModal.vue";

import { uniqBy } from "lodash-es";

import { useDebounceFn } from "@vueuse/core";

import utils from "@/common/utils/utils.js";

import vipModal from '@/socialMedia/Vip/vipModal.vue'

// AI写标题
import AIWritingTitle from "../../components/AIWritingTitle/index.vue"


export default defineComponent({
  props: {
    title_list: {
      type: Array,
      default: [],
    },
    activeKey: {
      type: Number,
      default: "",
    },
    // 发布类型
    PlatFormValue: {
      type: String,
      default: "",
    },
    // 用户列表
    accountList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    ismiaoshu: {
    type: Boolean,
    default: false,
    }
  },
  components: {
    PlusOutlined,
    QuestionCircleOutlined,
    AIExpansion,
    vipModal,
    DeleteOutlined,
    ExclamationCircleOutlined,
    CloseOutlined,
    QuestionCircleOutlined,
    RiskWordDetection,
    TextImitationDialog,
    CopyLibraryModal,
    TopicImportModal,
    AIWritingTitle
  },
  setup(props, context) {
    const state = reactive({
      visible: false,
      titleList: [],
      AISpinging: false,
      TextImitationDialogRef: null,

      topicImporVisible: false, //话题导入弹框

      // 话题数组
      totalTopicList: [],
      selectTopicList: [],
      topicList: [],
      // 话题获取loading
      topListLoading:false
    });

    // 充值弹窗
    const vipModalRef = ref(null)
    const vipVisible = ref(false)
    // 用户id
    const accountId = computed(() => {
      if (!props.accountList.length) {
        return ''
      }
      return props.accountList[0].id
    })
    const showDrawer = (openType) => {
      state.titleList = JSON.parse(JSON.stringify(props.title_list));
      if (openType == "add") {
        state.titleList.push({
          title: `标题${state.titleList.length + 1}`,
          key: state.titleList.length + 1,
          text: "",
          caption: "",
          hashtag_name: [],
          ai_keyword_group_id: null,
          ai_keyword_id: null,
          keyWordsGroupList: [],
          keyWordsList: [],
          isSpining: false,
        });
        getOptionList();
      }

      state.activeKey = props.activeKey;
      state.visible = true;
      if (props.PlatFormValue == 'xiaohongshu' && accountId.value) {
       XHS_Status.debouncedFn()
      }
    };
    const route = useRoute();
    // 路由信息
    const PlatFormValue = computed(() => {
      return route.query.platform;
    });
    const onClose = () => {
      let isChange = _.isEqual(
        state.titleList,
        JSON.parse(JSON.stringify(props.title_list))
      );
      if (isChange) {
        state.visible = false;
        formRef.value.resetFields();
      } else {
        Modal.confirm({
          title: "提示",
          icon: createVNode(ExclamationCircleOutlined),
          content: "当前页操作还未保存，直接离开数据不会保存和更新",
          cancelText: "取消",
          okText: "确定",
          onOk() {
            state.visible = false;
            formRef.value.resetFields();
          },
          onCancel() {},
        });
      }
    };
    // 添加标题
    const addTitle = () => {      
      state.titleList.push({
        title: `标题${state.titleList.length + 1}`,
        key: state.titleList.length + 1,
        text: "",
        caption: "",
        hashtag_name: [],
        ai_keyword_group_id: null, //关键词组id
        ai_keyword_id: null, //关键词id
        keyWordsGroupList: state.titleList[0].keyWordsGroupList, //关键词组列表
        keyWordsList: [], //关键词下拉列表
        isSpining: false,
        AISpining: false,
      });
    };
    // 最大标题长度及提示
    const TitleTextTipRules = computed(() => {
      if (PlatFormValue.value == "douyin") {
        return {
          tips: "标题不能超过30字限制(含空格)。",
          maxlength: 30,
        };
      } else if (PlatFormValue.value == "kuaishou") {
        return {
          tips: "标题不能超过30字限制(含空格)。",
          maxlength: 30,
        };
      } else if (PlatFormValue.value == "weixinshipinhao") {
        return {
          tips: "标题不能包含特殊字符，符号仅支持书名号、引号、冒号、加号、问号、百分号、摄氏度，逗号可用空格代替。且标题不能超过16字限制(含空格)。",
          maxlength: 16,
        };
      } else if (PlatFormValue.value == "xiaohongshu") {
        return {
          tips: "标题不能超过20字限制(含空格)。",
          maxlength: 20,
        };
      } else if (PlatFormValue.value == "bilibili") {
        return {
          tips: "标题不能超过80字限制(含空格)。",
          maxlength: 80,
        };
      } else {
        return {
          tips: "标题不能超过30字限制(含空格)。",
          maxlength: 30,
        };
      }
    });
    // 最大描述长度及提示
    const CapttionTipRules = computed(() => {
      if (PlatFormValue.value == "douyin") {
        return {
          tips: "字数不能超过1000字限制(含空格)。",
          maxlength: 1000,
        };
      } else if (PlatFormValue.value == "kuaishou") {
        return {
          tips: "不能超过500字限制(含空格)。",
          maxlength: 500,
        };
      } else if (PlatFormValue.value == "weixinshipinhao") {
        return {
          tips: "不能包含特殊字符，符号仅支持书名号、引号、冒号、加号、问号、百分号、摄氏度，逗号可用空格代替。且标题不能超过16字限制(含空格)。",
          maxlength: 1000,
        };
      } else if (PlatFormValue.value == "xiaohongshu") {
        return {
          tips: "不能超过1000字限制(含空格)。",
          maxlength: 1000,
        };
      } else if (PlatFormValue.value == "bilibili") {
        return {
          tips: "不能超过250字限制(含空格)。",
          maxlength: 250,
        };
      }
    });
    const deleteTitle = (index) => {
      if (AILoading.value) {
        return message.warning("AI扩写生成中请耐心等待");
      }
      if (state.titleList.length <= 1) {
        return message.warning("至少保留一个标题");
      } else {
        Modal.confirm({
          title: "删除标题",
          icon: createVNode(ExclamationCircleOutlined),
          content: "确定删除标题吗？",
          cancelText: "取消",
          okText: "确定",
          onOk() {
            state.titleList.splice(index, 1);
            state.titleList.forEach((item, index) => {
              item.title = `标题${index + 1}`;
            });
            message.success("删除成功");
            console.log(state.titleList);
          },
          onCancel() {},
        });
      }
    };
    const tagChange = (event, item, optionsList) => {
      if (event.length && event[event.length - 1].length > 10) {
        message.warning("单个话题长度不能超过10个字符");
        item.hashtag_name[item.hashtag_name.length - 1] = item.hashtag_name[
          item.hashtag_name.length - 1
        ].substring(0, 10);
        // 根据选中的值替换成 label
        item.hashtag_name = item.hashtag_name.map((tag) => {
          const option = optionsList?.find((ele) => ele.value == tag);
          return option ? option.label : tag;
        });
      }
      if (event.length > 5) {
        message.warning("最多添加5个标签");
        item.hashtag_name = item.hashtag_name.filter((tag, index) => index < 5);
      }
    };
    const formRef = ref();
    const submitHandle = () => {
      formRef.value
        .validate()
        .then((res) => {
          const filterList = state.titleList.filter(
            (item) => item.caption.trim().length || item.text.trim().length > 0
          );
          if (props.PlatFormValue == 'xiaohongshu') {
            filterList.forEach((filter) => {
              filter.hashtag_name = state.totalTopicList.filter(item => filter.hashtag_name.includes(item.key))
            })
            
          } else {
            filterList.forEach((filter) => {
              filter.hashtag_name = filter.hashtag_name.map((value) => {
                const found = filter?.keyWordsList?.find(item => item.value == value);
                return found ? found.label : value;
              });
            })
          }

          console.log(filterList, '过滤出来的小红书最终话题数据');


          context.emit("success", filterList);
          state.visible = false;
        })
        .catch((err) => {
          console.log(err);
        });
    };
    // AI扩写
    const addAIExpansion = () => {
      aiExpansionRef.value && aiExpansionRef.value.showModal();
    };
    // AI扩写弹窗成功回调
    const onConfirmAIExpansion = (arr) => {
      aiExpansionRef.value && aiExpansionRef.value.cancelClick();
      if (arr) {
        state.titleList = [];
        arr.map((item) => {
          state.titleList.push({
            title: `标题${state.titleList.length + 1}`,
            caption: item.text,
            key: state.titleList.length + 1,
            text: "",
            hashtag_name: [],
            ai_keyword_group_id: item.ai_keyword_group_id,
            ai_keyword_id: item.ai_keyword_id,
            keyWordsGroupList: item.keyWordsGroupList,
            keyWordsList: item.keyWordsList,
            isSpining: false,
          });
        });
      }
    };
    // 风险词检测
    const riskWordDetection = ref(null);
    const riskWordDetnHandle = () => {
      let titleArr = state.titleList?.map((item) =>
        item.text ? item.text : item.caption
      );
      const isImpty = titleArr?.some((ele) => ele.trim().length > 0);
      if (isImpty) {
        riskWordDetection.value &&
          riskWordDetection.value.showDrawer(titleArr, "release_title");
      } else {
        message.warning("请输入标题");
      }
    };

    // 文案仿写
    const openFangxie = () => {
      state.TextImitationDialogRef.showModal();
    };
    // AI扩写组件实例
    const aiExpansionRef = ref(null);
    const AILoading = computed(() => {
      return aiExpansionRef.value && aiExpansionRef.value.AILoading;
    });
    const AIExpanSionCount = computed(() => {
      return aiExpansionRef.value && aiExpansionRef.value.AIExpanSionCount;
    });
    const AIExpanSionTotal = computed(() => {
      return aiExpansionRef.value && aiExpansionRef.value.AIExpanSionTotal;
    });
    const AIExpansionPercent = computed(() => {
      return (
        (
          (aiExpansionRef.value && aiExpansionRef.value.AIExpanSionCount) /
          (aiExpansionRef.value && aiExpansionRef.value.AIExpanSionTotal)
        ).toFixed(1) * 100
      );
    });

    const keyWordsGroupList=ref([])
    // 获取关键词组下拉列表
    const getOptionList = () => {
      request
        .get("/work_ai", "/user/filmrelease/ai/keyword", { pagesize: 0 })
        .then((res) => {
          state.titleList.forEach((item) => {
            item.keyWordsGroupList = res.result?.data?.map((item) => {
              return {
                label: item.extraction_word,
                value: item.id,
              };
            });
          });
          keyWordsGroupList.value = res.result?.data?.map((item) => {
            return {
              label: item.extraction_word,
              value: item.id,
            };
          });
        })
        .finally(() => {});
    };
    // 获取关键词下拉列表
    const groupSelChange = (item, index) => {
      state.titleList[index].ai_keyword_id = "";
      state.titleList[index].hashtag_name = [];
      state.titleList[index].keyWordsList = null;
      if (state.titleList[index].ai_keyword_group_id) {
        state.titleList[index].isSpining = true;
        getKeywordMergeList(state.titleList[index].ai_keyword_group_id, true, index);
      }
    };

    const getKeywordMergeList = (ai_keyword_id, multiple = false, index) => {
      let params = {
        page: 0,
        ai_keyword_id,
        word: "",
      };
      request
        .get("/work_ai", "/user/filmrelease/ai/keywordMerge/list", params)
        .then((successRes) => {
          if (multiple) {
            state.titleList[index].keyWordsList = successRes?.result?.map(
              (ele) => {
                return {
                  value: ele.id,
                  label: ele.merge_keyword,
                };
              }
            );
            state.titleList[index].isSpining = false;
          } else {
            state.titleList.forEach((item) => {
              item.keyWordsList = successRes?.result?.map((ele) => {
                return {
                  value: ele.id,
                  label: ele.merge_keyword,
                };
              });
            });
          }
        });
    };

    const handleAIRequest = async (item) => {
      if (item.labelType == "title" && item.text.trim().length <= 0) {
        return message.error("请先输入标题内容");
      } else if (item.labelType == "desc" && item.caption.trim().length <= 0) {
        return PlatFormValue.value == "xiaohongshu"
          ? message.error("请输入作品简介")
          : message.error("请输入内容");
      }

      try {
        // 查看用户的点数是否足够消耗
        await utils.aiTextGet()
        try {
          // 消耗规则
          const rule = await utils.consumptionPointRule()
          // 获取提示
          const content = utils.ruleTips({ res: rule, key: "ai_text_point" })
          // 弹出提示
          await utils.md({ content })
          // 弹窗确认消耗
        } catch (error) {
          return
        }
      } catch (error) {
        // 打开充值, 接着打开点数购买
        vipVisible.value = true
        vipModalRef.value && vipModalRef.value.openBuyVisible()
        return
      }

      let captionText = item.caption;
      if (item.labelType == "desc" && item.hashtag_name.length) {
        // 将 hashtag_name 中的每个标签加上 '#' 并合并成一个字符串
        const hashtags = item.hashtag_name.map((tag) => `#${tag}#`).join(",");
        captionText = `${captionText}${hashtags}`;
      }
      console.log(captionText);
      const params = {
        is_text_rewrite: item.clickType == "AIRewriting" ? 1 : 0, // 0-扩写AIExpand 1-改写AIRewriting
        ai_keyword_id: item.ai_keyword_id,
        ai_keyword_group_id: item.ai_keyword_group_id,
        content: item.labelType == "title" ? item.text : captionText,
        ai_type: item.labelType, //扩写或者改写类型 desc-描述的扩写或者改写 title-标题的扩写或者改写
        platform: PlatFormValue.value, //扩写或者改写平台
      };
      state.AISpinging = true;

      try {
        const successRes = await request.post(
          "work_ai",
          "/user/filmrelease/ai/generate_title",
          params
        );
        if (!successRes || !successRes.result) {
          state.AISpinging = false;
          return message.error("AI扩写生成失败，状态id丢失");
        }

        const timerId = setInterval(async () => {
          try {
            const statusRes = await request.get(
              "/work_ai",
              "/user/filmrelease/ai/generate_title/status",
              { task_id: successRes.result }
            );
            if (
              statusRes.result.status === "success" ||
              statusRes.result.status === "error"
            ) {
              if (statusRes.result.data.length) {
                if (item.clickType == "AIRewriting") {
                  // 标题AI改写
                  if (item.labelType == "title") {
                    state.titleList[item.index].text = statusRes.result.data[0];
                  } else {
                    // 简介AI改写
                    state.titleList[item.index].caption =
                      statusRes.result.data[0];
                    state.titleList[item.index].hashtag_name =
                      statusRes?.result?.topic[0]
                        ?.filter((ele) => ele.length > 0)
                        ?.map((ele) => ele.substring(0, 10)) || [];
                  }
                } else {
                  if (item.labelType == "title") {
                    // 标题AI扩写
                    state.titleList.push({
                      ...item,
                      ai_keyword_group_id: null,
                      ai_keyword_id: null,
                      title: `标题${state.titleList.length + 1}`,
                      text: statusRes.result.data[0],
                    });
                  } else {
                    // 简介AI扩写
                    state.titleList.push({
                      ...item,
                      ai_keyword_group_id: null,
                      ai_keyword_id: null,
                      hashtag_name:
                        statusRes?.result?.topic[0]
                          ?.filter((ele) => ele.length > 0)
                          ?.map((ele) => ele.substring(0, 10)) || [],
                      title: `标题${state.titleList.length + 1}`,
                      caption: statusRes.result.data[0],
                    });
                  }
                }
              } else {
                message.error("AI生成内容失败");
              }
              clearInterval(timerId);
              state.AISpinging = false;
            }
          } catch (statusErr) {
            console.log(statusErr);
            state.AISpinging = false;
            clearInterval(timerId);
          }
        }, 1000);
      } catch (errorRes) {
        console.log(errorRes);
        state.AISpinging = false;
      }
    };

    // 获得文案仿写返回的数据
    const getTextArr = (list) => {
      console.log(list, "传递过来的list");
      console.log(state.titleList, "表单渲染的数组");
      // 计算需要补充的项数
      const diff = list.length - state.titleList.length;

      if (diff > 0) {
        // 补充 state.titleList
        for (let i = 0; i < diff; i++) {
          state.titleList.push({
            title: `标题${state.titleList.length + 1}`,
            key: state.titleList.length + 1,
            text: "",
            caption: "",
            hashtag_name: [],
            ai_keyword_group_id: null, // 关键词组id
            ai_keyword_id: null, // 关键词id
            keyWordsGroupList: state.titleList[0].keyWordsGroupList, // 关键词组列表
            keyWordsList: [], // 关键词下拉列表
            isSpining: false,
            AISpining: false,
          });
        }
      }

      list.forEach((item, index) => {
        state.titleList[index].caption = item.content;
        state.titleList[index].text = item.title;
      });

      state.TextImitationDialogRef.closeModal();
    };

    // 文案库导入
    let copyLibraryModal = ref(null); //文案库导入组件实例

    const copywritingImport = () => {
      copyLibraryModal.value && copyLibraryModal.value.showModal();
    };

    const closeChooseMaterial = async (data) => {
      data.forEach((item, index) => {
        state.titleList.forEach((titlItem) => {
          item.keyWordsGroupList = titlItem.keyWordsGroupList;
        });

        // item.keyWordsList = titlItem.keyWordsList
        item.title = `标题${index + 1}`;
        item.key = index + 1;
        item.hashtag_name = state.titleList?.[index]?.hashtag_name || [];
        item.caption = item.material_content;
        item.ai_keyword_group_id = undefined;
        item.isSpining = false;
      });
      state.titleList = data;
      copyLibraryModal.value && copyLibraryModal.value.closeModal();
    };

    // 话题导入
    const topicImport = () => {
      state.topicImporVisible = true;
    };

    const closeChange = () => {
      state.topicImporVisible = false;
    };

    // emit选择话题
    const importChange = ({ changeData }) => {
      if (changeData.ai_keyword_group_id || changeData.hashtag_name) {
        state.titleList.forEach((item) => {
          item.ai_keyword_group_id = changeData.ai_keyword_group_id;
          item.hashtag_name = changeData.hashtag_name;
        });
        if (changeData.hashtag_name) {
          getKeywordMergeList(changeData.ai_keyword_group_id);
        }
      }

      state.topicImporVisible = false;
    };


    const XHS_Status = reactive({
      // 小红书 接收到组件选择的话题
      XHS_importChange: (list) => {
        console.log(list, '小红书选择的话题');
        console.log(state.titleList, 'titleList');
        
        // 添加源数据
        state.topicList.push(...list)
        state.totalTopicList.push(...list)
        // 去重
        state.totalTopicList = uniqBy(state.totalTopicList, "key");
        state.topicList = uniqBy(state.topicList, "key");
        state.titleList.forEach((item) => {
          // item.ai_keyword_group_id = '';
          item.hashtag_name = list.map(ele => ele.key);
        });
        console.log(state.titleList, 'titleList.添加结束');
        state.topicImporVisible = false;

      },

      getTopicList: async (keyword = "") => {
        // 话题加载中
        // state.topListLoading = true
        const { result } = await request.post(
          "/work_ai",
          "/org/platform/account/topic",
          { id: accountId.value, keyword }
        );
        console.log(result, '话题123123');
        
        // state.topListLoading = false
        state.topicList = result;
        state.totalTopicList.push(...state.topicList);
        state.totalTopicList = uniqBy(state.totalTopicList, "key");
      },

      handleChange: (e) => {
        if (e.length) {
          formRef.value.hash_tag = state.totalTopicList.filter((item) =>
            e.includes(item.key)
          );
        }
        if (e && e.length > 19) {
          message.warning("最多选择20个话题");
        }
},

      debouncedFn: useDebounceFn((e) => {
        XHS_Status.getTopicList(e);
      }, 500),

      handleSearch: (keyword) => {
        XHS_Status.debouncedFn(keyword);
      }
    })

    const writingTitleVisible=ref(false)

    // AI批量写标题
    const titleListNum=ref(0)
    const AIBatchWritingTitles=()=>{
      titleListNum.value = state.titleList.filter((item)=>item.caption).length
      writingTitleVisible.value = true
    }

    
const closeWritingTitleChange=()=>{
  writingTitleVisible.value = false
}

const AIWritingTitles=(index)=>{
  writingTitleVisible.value = true
}

const submitChange=(list)=>{
  state.titleList =[]
  list.forEach((item)=>{
    state.titleList.push({
        title: `标题${state.titleList.length + 1}`,
        key: state.titleList.length + 1,
        caption: item.title,
        text: item.title,
        hashtag_name: [],
        ai_keyword_group_id: null,
        ai_keyword_id: null,
        keyWordsGroupList: [],
        isSpining: false,
      });
  })

  setTimeout(()=>{
    state.titleList = state.titleList.map(item => {
        return {
            ...item,
            keyWordsGroupList: keyWordsGroupList.value
        };
    });
    writingTitleVisible.value = false
  },50)
}

watch(
  ()=>state.visible,
  (val)=>{
    if(val){
      getOptionList();
    }
  }
)

    return {
      ...toRefs(state),
      vipModalRef,
      vipVisible,
      accountId,
      XHS_Status,
      showDrawer,
      onClose,
      addTitle,
      deleteTitle,
      tagChange,
      formRef,
      submitHandle,
      addAIExpansion,
      onConfirmAIExpansion,
      riskWordDetection,
      riskWordDetnHandle,
      aiExpansionRef,
      AILoading,
      AIExpansionPercent,
      AIExpanSionCount,
      AIExpanSionTotal,
      getOptionList,
      groupSelChange,
      PlatFormValue,
      TitleTextTipRules,
      handleAIRequest,
      CapttionTipRules,
      openFangxie,
      getTextArr,
      copywritingImport,
      copyLibraryModal,
      closeChooseMaterial,
      topicImport,
      closeChange,
      importChange,
      AIBatchWritingTitles,
      closeWritingTitleChange,
      submitChange,
      writingTitleVisible,
      AIWritingTitles,
      titleListNum
    };
  },
});
</script>



<style lang="less">
.kuaishou_good {
.ss-select-dropdown   {
  display: none !important;
}
}




</style>

<style lang="less" scoped>
.title_item {
  border: 1px solid #e0e0e0;
  padding: 10px 10px 0 10px;
  border-radius: 5px;
  margin-top: 15px;

  .AI_expend {
    text-align: right;
    padding: 5px 0;

    :deep(.ss-btn > .anticon + span, .ss-btn > span + .anticon) {
      margin-left: 0 !important;
    }
  }
}

.del_btn {
  &:hover {
    color: var(--ss-primary-color);
  }
}

// 去除校验失败边框颜色
:deep(
    .ss-form-item-has-error
      .ss-select:not(.ss-select-disabled):not(.ss-select-customize-input)
      .ss-select-selector
  ) {
  border-color: #fff !important;
  // padding-left: 10px !important;
}

:deep(.ss-form-item-explain-error) {
  padding-left: 10px !important;
}

:deep(textarea) {
  &::-webkit-scrollbar {
    width: 3px;
  }
}

.textarea {
  &::-webkit-scrollbar {
    display: none !important;
  }

  &::-webkit-scrollbar-track {
    width: 5px;
    background-color: transparent;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(193, 193, 193, 0.5);
    background-clip: padding-box;
    min-height: 28px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }
}

:deep(.ss-select-multiple .ss-select-selection-item) {
  background: #d5e3f4 !important;
}

.drawer-header {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  color: rgba(0, 0, 0, 0.85);
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  border-radius: 2px 2px 0 0;

  .drawer-header-title {
    display: flex;
    align-items: center;
    font-size: 16px;

    .drawer-close {
      display: inline-block;
      margin-right: 12px;
      color: rgba(0, 0, 0, 0.45);
      font-weight: 700;
      font-size: 16px;
      font-style: normal;
      background: transparent;
      cursor: pointer;
    }

    .drawer-title {
      font-weight: 600;
    }
  }
}

.title_tip {
  :deep(.ss-btn[disabled]) {
    display: flex !important;
  }
}

.kuaishou_good {
  width: 300px;
  height: 300px;
  border: 1px solid #000;
  background-color: pink;
}
</style>
